import React from 'react'
import {
  UdPage,
  UdPageHeader,
  UdFilter,
  udConfigProvider,
  http,
  BaseListPage,
  IBaseListPageState,
  routeUtils,
  IUdFormItem,
  UdDateRangePicker,
} from '@/lib'
import _ from 'lodash'
import { BackTop, Tabs, Select, Badge, Spin } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import classNames from 'classnames'
import './style.scss'
import apis from '@/apis/TodoList'
import comApis from '@/apis'
import { AxiosResponse } from 'axios'
import { PaginationConfig } from 'antd/lib/table'
import udMainStore from '@/store/UdMain'
import StockCheckTable from '../StockCheck/Table'
import MonthlyQuotaApplicationTable from '../MonthlyQuotaApplication/Table'
import MonthlyQuotaReleaseTable from '../MonthlyQuotaRelease/Table'
import QuotaAdjustmentTable from '../QuotaAdjustment/Table'
import QuotaImportTable from '../QuotaImport/Table'
import QuotaFreezeTable from '../QuotaFreeze/Table'
import QuotaTransferTable from '../QuotaTransfer/Table'
// import { ETodoTabTypes, todoTabUrls, todoTabTypes } from './configOption'
import { ETodoTabTypes, todoTabTypes } from './configOption'
import CustomrankImportTable from '../CustomrankImport/Table'
import CustomrankAdjustTable from '../CustomrankAdjust/Table'
import TotalProfitTable from '../TotalProfit/Table'
import WorkingCapitalTable from '../WorkingCapital/Table'
import OperatingItemsTable from '../OperatingItems/Table'
import DealersProcess from '../DealersProcess/Table'

const { TabPane } = Tabs
const { Option } = Select

// 任务状态
export const settledReviewstatusEnum = {
  0: '审批中',
  1: '审批通过',
  2: '审批不通过',
}

export default class Index extends BaseListPage<any, ITodoListState> {
  /** 条件过滤器的表单对象 */
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  /** 滚动条容器 */
  protected pageContainer = udConfigProvider.ui.getPageContainer()

  private statusOptions = Object.keys(settledReviewstatusEnum).map(key => ({
    value: key,
    title: settledReviewstatusEnum[key],
  }))

  private todoTabTypes: any = todoTabTypes

  public brandList = udMainStore.brandList
  public initialBrandValue = udMainStore.initialBrandValue

  private initialShowTabKey = this.todoTabTypes.find(tab => tab.hasAuth)?.key

  constructor(props) {
    super(props)
    this.state = {
      title: '我的待办',
      queryApi: params => {
        return http.get(apis.settledReviewList, { params: { ...params, type: this.state.todoType } })
      },
      columns: [],
      conditions: [
        {
          id: 'brandCode',
          label: '销售组织',
          initialValue: undefined,
          render: (
            <Select allowClear>
              {this.brandList.map(({ value, title }) => (
                <Option key={value} value={value}>
                  {title}
                </Option>
              ))}
            </Select>
          ),
        },
        {
          id: 'status',
          label: '任务状态',
          render: (
            <Select>
              {this.statusOptions.map(({ value, title }) => (
                <Option key={value} value={value}>
                  {title}
                </Option>
              ))}
            </Select>
          ),
        },
        {
          id: 'startUserName',
          label: '发起人',
        },
        { id: ['startTime', 'endTime'], label: '起止时间', render: <UdDateRangePicker /> },
        {
          label: '列表排序',
          id: 'orderBy',
          initialValue: 'desc',
          render: (
            <Select allowClear={false}>
              <Select.Option value="desc">时间降序</Select.Option>
              <Select.Option value="asc">时间升序</Select.Option>
            </Select>
          ),
        },
      ],
      rowKey: 'id',
      querying: false,
      todoType: 1,
      needTodoNumber: 0,
      hasTodoNumber: 0,
      myTodoNumber: 0,
      showTabKey: this.initialShowTabKey,
      tabDatas: {}, // tab列表数据容器
      tabPageDatas: {}, // tab列表分页数据容器
      tabsList: JSON.parse(JSON.stringify(todoTabTypes)),
      loading: false,
    }
  }
  public componentWillMount() {
    super.componentWillMount()
    const searchString = this.props.location.search
    const { type, showTabKey } = routeUtils.searchStringToObject(searchString, {
      type: 1,
      showTabKey: this.initialShowTabKey,
    })
    const url = apis.getAllTodoList
    this.setState({
      todoType: type,
      showTabKey,
      queryApi: params => {
        params.processKey = showTabKey
        // 员工盘点列表和经销商盘点列表添加额外参数
        // if (showTabKey == ETodoTabTypes.DEALER_INVENTORY_CHECK) {
        //   params.processKey = 'JXSSTOCKAPPROVAL'
        // } else if (showTabKey == ETodoTabTypes.INVENTORY_CHECK) {
        //   params.processKey = 'STOCKAPPROVAL'
        // }
        setTimeout(this.getTabsCount)
        return http.get(url, { params: { ...params, type: this.state.todoType } })
      },
    })
  }
  public componentDidMount() {
    super.componentDidMount()
    this.getTodoNumber()
  }

  getTabsCount = () => {
    const { brandCode, startTime, endTime, startUserName } = this.getQueryParams() || {}
    const { todoType } = this.state

    if (todoType !== 1)
      return this.setState({
        tabsList: JSON.parse(JSON.stringify(todoTabTypes)),
      })
    http
      .get(apis.getAllTodoListTotal, {
        params: {
          brandCode,
          startTime: startTime || undefined,
          endTime: endTime || undefined,
          startUserName: startUserName || undefined,
        },
      })
      .then(({ data }: any) => {
        const { tabsList }: any = this.state
        this.setState({
          tabsList: tabsList.map((a: any) => ({
            ...a,
            count: data.find((item: any) => a.key === item.tabName)?.unreadCount || 0,
          })),
        })
      })
  }

  render() {
    const { conditions, needTodoNumber, hasTodoNumber, myTodoNumber, showTabKey, tabsList, loading } = this.state
    return (
      <Spin spinning={loading}>
        <UdPage className="list-page">
          {this.state.title && (
            <UdPageHeader
              title={this.state.title}
              subTitle={this.state.subTitle}
              affixProps={{ target: () => this.pageContainer }}
            />
          )}
          <div className="todo-types">
            <div
              className={classNames('type-item', this.state.todoType === 1 && 'active')}
              onClick={() => this.switchTodoTypeHandle(1)}
            >
              <div className="todo-title">待处理</div>
              <div className="todo-number">{needTodoNumber}个</div>
            </div>
            <div
              className={classNames('type-item', this.state.todoType === 2 && 'active')}
              onClick={() => this.switchTodoTypeHandle(2)}
            >
              <div className="todo-title">已处理</div>
              <div className="todo-number">{hasTodoNumber}个</div>
            </div>
            <div
              className={classNames('type-item', this.state.todoType === 3 && 'active')}
              onClick={() => this.switchTodoTypeHandle(3)}
            >
              <div className="todo-title">我发起的</div>
              <div className="todo-number">{myTodoNumber}个</div>
            </div>
          </div>
          <Tabs activeKey={showTabKey} onChange={this.switchTodoTabHandle}>
            {tabsList.map(
              todoTab =>
                todoTab.hasAuth && (
                  <TabPane
                    tab={
                      <Badge offset={[10, 0]} count={todoTab.count || 0}>
                        <div>{todoTab.title}</div>
                      </Badge>
                    }
                    key={todoTab.key}
                    disabled={todoTab.disabled}
                  >
                    {_.isArray(conditions) && conditions.length > 0 && (
                      <UdFilter
                        getForm={form => {
                          this.filterForm = form
                        }}
                        items={this.state.conditions}
                        onSearch={values => {
                          this.handleSearch(values)
                        }}
                        loading={this.state.loading}
                        resetAfter={this.filterReset}
                      />
                    )}
                    {showTabKey === todoTab.key && this.getShowTodoTab(todoTab.key)}
                  </TabPane>
                )
            )}
          </Tabs>
          {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
        </UdPage>
      </Spin>
    )
  }

  private getTodoNumber = () => {
    this.setState({ loading: true })
    http
      .get(apis.todoStatusNumber)
      .then(res => {
        const {
          processTaskWillAuditStatisticsResult,
          processTaskAuditedStatisticsResult,
          processInstanceApplyStatisticsResult,
        } = res.data
        const needTodoNumber = processTaskWillAuditStatisticsResult?.num || 0
        const hasTodoNumber = processTaskAuditedStatisticsResult?.num || 0
        const myTodoNumber = processInstanceApplyStatisticsResult?.num || 0
        this.setState({
          needTodoNumber,
          hasTodoNumber,
          myTodoNumber,
        })
      })
      .finally(() => {
        this.setState({
          loading: false,
        })
      })
  }

  protected query = () => {
    let promise: Promise<AxiosResponse>
    if (_.isFunction(this.state.queryApi)) {
      promise = this.state.queryApi(this.getQueryParams())
    }
    this.setState({ querying: true })
    promise
      .then(
        res => {
          const { showTabKey, tabDatas, tabPageDatas } = this.state
          let pagination = tabPageDatas[showTabKey] as PaginationConfig
          if (!pagination) {
            pagination = {}
          }
          // if (pagination) {
          pagination.current = res.data[BaseListPage.resFieldKeys.number]
          pagination.pageSize = res.data[BaseListPage.resFieldKeys.size]
          pagination.total = res.data[BaseListPage.resFieldKeys.totalElements]
          // }
          tabDatas[showTabKey] = res.data?.content
          tabPageDatas[showTabKey] = pagination
          this.setState({
            tabDatas,
            tabPageDatas,
          })
        },
        err => {
          const { showTabKey, tabDatas, tabPageDatas } = this.state
          let pagination = { ...tabPageDatas[showTabKey] }
          if (pagination && pagination.total) {
            pagination.total = 0
          }
          const currentPageDatas = { [showTabKey]: pagination }
          const currentDatas = { [showTabKey]: [] }
          this.setState({
            tabDatas: { ...tabDatas, ...currentDatas },
            tabPageDatas: { ...tabPageDatas, currentPageDatas },
          })
        }
      )
      .finally(() => this.setState({ querying: false }))
  }

  /**
   * 处理条件过滤器查询事件
   */
  protected handleSearch = (values: any) => {
    let p: any = {
      conditions: values,
      v: new Date().getTime(),
    }
    // if (this.state.pagination) {
    p.page = 1
    // }
    // 添加列表头部选择的状态
    p.type = this.state.todoType
    this.handleParamsChange(p)
  }

  /**
   * 列表检索条件发生改变时
   */
  protected handleTableChange = (pagination, filters, sorter, extra) => {
    let baseConditions = this.queryParams.conditions
    let p: any = {
      conditions: baseConditions,
      v: new Date().getTime(),
    }
    p.page = pagination.current
    p.size = pagination.pageSize
    p.type = this.state.todoType
    this.handleParamsChange(p)
  }

  private switchTodoTypeHandle = todoType => {
    this.setState(
      {
        todoType,
      },
      () => {
        this.getTodoNumber()
        this.pushQueryParams({ type: todoType }, false)
      }
    )
  }

  private switchTodoTabHandle = key => {
    let url = apis.getAllTodoList
    this.setState(
      {
        showTabKey: key,
        queryApi: params => {
          params.processKey = key
          // 员工盘点列表和经销商盘点列表添加额外参数
          // if (key == ETodoTabTypes.DEALER_INVENTORY_CHECK) {
          //   params.processKey = 'JXSSTOCKAPPROVAL'
          // } else if (key == ETodoTabTypes.INVENTORY_CHECK) {
          //   params.processKey = 'STOCKAPPROVAL'
          // }
          setTimeout(this.getTabsCount)
          return http.get(url, { params: { ...params, type: this.state.todoType } })
        },
      },
      () => {
        // this.query()
        this.pushQueryParams({ type: this.state.todoType, showTabKey: key }, false)
      }
    )
  }

  private getShowTodoTab = key => {
    let render
    const { querying, todoType } = this.state
    const dataSource = this.state.tabDatas[key] || []
    const pagination = this.state.tabPageDatas[key]
    const { history } = this.props
    const { brandCode,orderBy='desc' } = this.getQueryParams() || {}
    const tableProps = {
      loading: querying,
      dataSource,
      pagination,
      onChange: this.handleTableChange,
      history,
      todoType,
      brandCode,
    }
    switch (key) {
      case ETodoTabTypes.STOCKAPPROVAL: // 库存盘点
        render = <StockCheckTable {...tableProps} todoType={this.state.todoType} refresh={this.switchTodoTypeHandle} />
        break
      case ETodoTabTypes.JXSSTOCKAPPROVAL: // 经销商库存盘点
        render = <StockCheckTable {...tableProps} stockType="JXSSTOCKAPPROVAL" />
        break
      case ETodoTabTypes.QUOTASALEMAN: // 月度配额申请
        render = <MonthlyQuotaApplicationTable {...tableProps} />
        break
      case ETodoTabTypes.ORGAPPROVAL: // 月度配额下达
        render = <MonthlyQuotaReleaseTable {...tableProps} />
        break
      case ETodoTabTypes.QUOTAADJUST: //* 配额调整
        render = (
          <QuotaAdjustmentTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.QUOTACHANGE: // 月度配额转移
        render = <QuotaTransferTable {...tableProps} />
        break
      case ETodoTabTypes.QUOTAIMPORT: //*配额导入
        render = (
          <QuotaImportTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.QUOTA_FREEZE: //*解冻冻结
        render = (
          <QuotaFreezeTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.USER_CUSTOMRANK_IMPORT: //*等级权益导入
        render = (
          <CustomrankImportTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.USER_CUSTOMRANK_ADJUST: //*等级权益调整
        render = (
          <CustomrankAdjustTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.WORKING_CAPITAL: //*运营资金
        render = (
          <WorkingCapitalTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.GROSS_PROFIT: //*税前总利润
        render = (
          <TotalProfitTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.OPERATING_MAIN: //*经营品项
        render = (
          <OperatingItemsTable
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
      case ETodoTabTypes.AGENT_PROCESS: //*经销商待办
        render = (
          <DealersProcess
            {...tableProps}
            orderBy={orderBy}
            todoType={this.state.todoType}
            refresh={this.switchTodoTypeHandle}
            key={Date.now()}
          />
        )
        break
    }
    return render
  }
}

interface ITodoListState extends IBaseListPageState {
  todoType: number
  needTodoNumber: number
  hasTodoNumber: number
  myTodoNumber: number
  showTabKey: string
  tabDatas: any
  tabPageDatas: any
  tabsList: any[]
  loading: boolean
}
